package com.lihaozhe.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import com.lihaozhe.util.token.CodeInSession;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 李昊哲
 * @version 1.0.0
 * 2021/12/16 10:08
 */
@RestController
@RequestMapping("/code")
public class CodeController {
    public final static String verificationCodeInSession = "verificationCodeInSession";
    @GetMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(156, 44);
        // 重新生成code
        lineCaptcha.createCode();
        // 获取验证码字符串
        String code = lineCaptcha.getCode();
        // 验证码字符串存储到sesssion中
        HttpSession session = request.getSession();
        // 该验证码有效期为60秒
        CodeInSession codeInSession = new CodeInSession(code, 60L);
        session.setAttribute(verificationCodeInSession,codeInSession);
        // 获取输出流
        ServletOutputStream outputStream = response.getOutputStream();
        // 将验证码图片输出到页面
        lineCaptcha.write(outputStream);
        outputStream.flush();
        outputStream.close();
    }
}